<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="园区" prop="parkName">
        <el-select clearable v-model="queryParams.parkId" placeholder="请选择园区">
          <el-option v-for="item in buiParkList" :key="item.id" :label="item.parkName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="楼栋" prop="buildingName">
        <el-input
          v-model="queryParams.roomNum"
          placeholder="请输入房源编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="房源编号" prop="roomNum">
        <el-input
          v-model="queryParams.roomNum"
          placeholder="请输入房源编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="楼层" prop="floor">
        <el-input
          v-model="queryParams.floor"
          placeholder="请输入楼层"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="房源类型" prop="roomType">
        <el-select
          clearable
          v-model="queryParams.roomType"
          placeholder="请选择房源类型"
        >
          <el-option
            v-for="item in roomType"
            :key="item.dictCode"
            :label="item.dictLabel"
            :value="item.dictValue"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="使用性质" prop="state">
        <el-select
          clearable
          v-model="queryParams.state"
          placeholder="请选择使用性质"
        >
          <el-option
            v-for="item in roomUseState"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['park:buiRoom:add']"
        >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['park:buiRoom:edit']"
        >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['park:buiRoom:remove']"
        >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['park:buiRoom:export']"
        >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['park:buiRoom:edit']"
        >房源导入</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleFacilityImport"
          v-hasPermi="['park:buiRoom:export']"
        >配套导入
        </el-button>
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="buiRoomList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="房源编号" align="center" prop="roomNum" />
      <el-table-column label="园区" align="center" prop="parkName" />
      <el-table-column label="楼栋" align="center" prop="buildingName" />
      <el-table-column label="楼层" align="center" prop="floor" />
      <el-table-column label="房号" align="center" prop="houseNumber" />
      <el-table-column label="房源面积(m²)" align="center" prop="builtUpArea" />
      <el-table-column label="合同面积(m²)" align="center" prop="contractArea" />
      <el-table-column label="入驻企业" align="center" prop="enterpriseName" />
      <el-table-column label="房源类型" align="center" prop="roomTypeNew" />
      <el-table-column label="使用性质" align="center" prop="stateNew" />
      <el-table-column label="是否使用" align="center" prop="leaseStateNew" />
      <el-table-column label="附件份数" align="center" prop="fileAmount" />
      <el-table-column
        label="操作"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="showFileDowFn(scope.row)"
            v-hasPermi="['park:buiPark:edit']"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['park:buiRoom:edit']"
          >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['park:buiRoom:remove']"
          >删除</el-button
          >

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!--<el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据-->
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="facilityUpload.title"  :visible.sync="facilityUpload.open" width="400px" append-to-body>
      <el-upload
        ref="facilityUpload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="facilityUpload.headers"
        :action="facilityUpload.url + '?updateSupport=' + facilityUpload.updateSupport"
        :disabled="facilityUpload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!--<el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据-->
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFacilityForm">确 定</el-button>
        <el-button @click="facilityUpload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <FileDownPop v-if="showFilePop" @close="filePopClose" :fileList="fileList"></FileDownPop>
    <!-- 添加或修改房源对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" size='small' :model="form" :rules="rules" label-width="120px">

        <el-form-item label="园区" prop="parkId">
          <el-select clearable v-model="form.parkId"   @change="getBuildingList(form.parkId)" placeholder="请选择园区">
            <el-option
              v-for="item in buiParkList"
              :key="item.id"
              :label="item.parkNum"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼栋" prop="buildingId">
          <el-select
            clearable
            v-model="form.buildingId"
            placeholder="请选择楼栋"
          >
            <el-option
              v-for="item in buildingList"
              :key="item.id"
              :label="item.buildingNum"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-input v-model="form.floor" placeholder="请输入楼层" />
        </el-form-item>
        <el-form-item label="房号"  prop="houseNumber">
          <el-input @enter="getListBuiUnit()" @blur="getListBuiUnit()" v-model="form.houseNumber" placeholder="请输入房号" />
        </el-form-item>
        <el-form-item label="房源编号" prop="roomNum">
          <el-input disabled v-model="form.roomNum" placeholder="请先选择园区,楼栋。输入楼层" />
        </el-form-item>
        <el-form-item label="使用性质" prop="state">
          <el-select
            clearable
            v-model="form.state"
            placeholder="请选择使用性质"
          >
            <el-option
              v-for="item in roomUseState"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产权面积(㎡)" prop="builtUpArea">
          <el-input v-model="form.builtUpArea" placeholder="请输入产权面积" />
        </el-form-item>
        <el-form-item label="合同面积(㎡)" prop="contractArea">
          <el-input v-model="form.contractArea" placeholder="请输入合同面积" />
        </el-form-item>
        <el-form-item label="房源类型" prop="roomType">
          <el-select
            clearable
            v-model="form.roomType"
            placeholder="请选择房源类型"
          >
            <el-option
              v-for="item in roomType"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="房间配置" prop="capacity" v-if='form.roomType==="1"'>
          <el-input v-model="form.capacity" type="number" placeholder="请输入几人间(数字)" />
        </el-form-item>
        <el-form-item label="配套设施">
          <div class='facilityList' v-for='(item,index) in form.facilityList' :key='index'>
            <span>名称</span>
            <el-input v-model="item.facilityName"   />
            <span>规格</span>
            <el-input v-model="item.facilityModal"   />
            <span>数量</span>
            <el-input v-model="item.quantity"  />
            <i v-if='index===0' @click="addfacility" class="el-icon-circle-plus-outline"></i>
            <i v-else @click="delfacility(index)" class="el-icon-remove-outline"></i>
          </div>

        </el-form-item>
        <el-form-item label="是否使用" prop="leaseState">
          <el-select
            clearable
            v-model="form.leaseState"
            placeholder="请选择是否使用"
          >
            <el-option
              v-for="item in leaseStateList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="附件">
          <FileUpload  ref="fileupload"  :fileListTem="form.fileIdList" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listBuiRoom,
    getBuiRoom,
    delBuiRoom,
    addBuiRoom,
    updateBuiRoom,
  } from "@/api/parkAssets/buildingRoom";
  import { listBuiPark } from "@/api/parkAssets/enterCommunity";
  import { listBuiBuilding } from "@/api/parkAssets/building";
  import { listBuiUnit } from "@/api/parkAssets/buildingUnit";
  import FileUpload from "../components/FileUpload.vue";
  import { listData } from "@/api/system/dict/data";
  import { getToken } from "@/utils/auth";

  export default {
    name: "BuiRoom",
    components: {
      FileUpload,
    },
    data() {
      return {
        // 用户导入参数
        upload: {
          // 是否显示弹出层
          open: false,
          // 弹出层标题
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/park/buiRoom/importData"
        },
        facilityUpload: {
          // 是否显示弹出层
          open: false,
          // 弹出层标题
          title: '',
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + '/park/buiRoom/importFacilityData'
        },
        tempType:0,
        fileList:[],
        showFilePop:false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 房源表格数据
        buiRoomList: [],
        buiParkList: [],
        buildingList: [],
        leaseStateList:[{dictValue:"0",dictLabel:"否"},{dictValue:"1",dictLabel:"是"}],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          roomNum: null,
          floor: null,
          buildingId: null,
          builtUpArea: null,
          roomType: null,
          state: null,
          fileCount: null,
          parkId: null,
        },
        quantity: null,
        facilityName: null,
        facilityModal:null,
        roomType: [],
        roomUseState: [],
        // 表单参数
        form: {
          fileIdList: [],
          leaseState:"0"
        },
        // 表单校验
        rules: {
          builtUpArea: [
            { required: true, message: "房源面积不能为空", trigger: "blur" },
          ],
          // contractArea: [
          // { required: true, message: "合同面积不能为空", trigger: "blur" },
          // ],
          parkId: [
            { required: true, message: "园区不能为空", trigger: "change" },
          ],
          buildingId: [
            { required: true, message: "楼栋不能为空", trigger: "blur" },
          ],
          floor: [{ required: true, message: "楼层不能为空", trigger: "blur" }],
          houseNumber: [
            { required: true, message: "房号不能为空", trigger: "blur" },
          ],
        },
      };
    },
    created() {
      listBuiPark().then((response) => {
        this.buiParkList = response.rows;
      });

      this.getList();
    },
    methods: {
      /** 下载模板操作 */
      importTemplate() {
        if (this.tempType == 0) {
          this.download('park/buiRoom/importTemplate', {
            ...this.queryParams
          }, `房源导入模板.xlsx`)
        } else {
          this.download('park/buiRoom/importFacilityTemplate', {
            ...this.queryParams
          }, `房源配套导入模板.xlsx`)
        }
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = '房源导入'
        this.upload.open = true
        this.tempType = 0
      },

      handleFacilityImport() {
        this.facilityUpload.title = '公寓配套导入'
        this.facilityUpload.open = true
        this.tempType = 1

      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        if (this.tempType == 0){

          this.upload.isUploading = true
        }else {
          this.facilityUpload.isUploading = true;
        }
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        if (this.tempType == 0){
          this.upload.open = false
          this.upload.isUploading = false
          this.$refs.upload.clearFiles()
        }else {
          this.facilityUpload.open = false
          this.facilityUpload.isUploading = false
          this.$refs.facilityUpload.clearFiles()
        }
        this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
        this.getList();
      },
      submitFacilityForm(){
        this.$refs.facilityUpload.submit();
      },

      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      filePopClose(){
        this.showFilePop=false
      },
      showFileDowFn(row){
        this.reset();
        const id = row.id || this.ids;
        getBuiRoom(id).then((response) => {
          response.data.fileList.forEach((element) => {
            let url= "http://" + element.url
            this.fileList.push({
              name: element.name,
              id: element.id,
              url,
            })
          });
        });
        this.showFilePop=true
      },
      addfacility() {
        this.form.facilityList.push({
          facilityName: null,
          facilityModal: null,
          quantity: null,
        });
      },
      delfacility(index) {
        this.form.facilityList.splice(index, 1);
      },
      getListFirst() {
        listData({ dictType: "room_type" }).then((response) => {
          this.roomType = response.rows;
        });
        listData({ dictType: "room_use_state" }).then((response) => {
          this.roomUseState = response.rows;
        });
      },
      //得到楼栋
      getBuildingList(value) {
        this.form.buildingId = "";
        this.buildingList = [];
        listBuiBuilding({ parkId: value }).then((response) => {
          this.buildingList = response.rows;
        });
      },
      getListBuiUnit() {
        console.log("enter out toach")
        if (this.form.parkId && this.form.buildingId && this.form.floor) {
          let buiPark = this.buiParkList.filter((item) => {
            return item.id == this.form.parkId;
          });
          let building = this.buildingList.filter((item) => {
            return item.id == this.form.buildingId;
          });
          this.form.roomNum = `${buiPark[0].parkNum}-${building[0].buildingNum}-${this.form.floor}-${this.form.houseNumber}`;
        }
      },
      /** 查询房源列表 */
      async getList() {
        this.loading = true;
        await this.getListFirst();
        listBuiRoom(this.queryParams).then((response) => {
          response.rows.forEach((item) => {
            this.roomType.forEach((itemType) => {
              //console.log("itemType",itemType.dictLabel,item.roomType)
              if (itemType.dictValue == item.roomType) {
                item.roomTypeNew = itemType.dictLabel;
              }
            });
            this.roomUseState.forEach((itemState) => {
              if (itemState.dictValue === item.state) {
                item.stateNew = itemState.dictLabel;
              }
            });
            if(item.leaseState =='1'){
              item.leaseStateNew ="是"
            }else {item.leaseStateNew ="否"}
          });
          this.buiRoomList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          roomNum: null,
          houseNumber: null,
          floor: null,
          buildingId: null,
          builtUpArea: null,
          roomType: null,
          state: "3",
          capacity: null,
          fileCount: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          contractArea: null,
          parkId: null,
          tenantId: null,
          fileIdList: [],
          leaseState:"0",
          facilityList: [
            {
              facilityName: null,
              facilityModal: null,
              quantity: null,
            },
          ],
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.form.fileIdList = [];
        this.title = "添加房源";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids;
        getBuiRoom(id).then((response) => {
          listBuiBuilding({ parkId: response.data.parkId }).then((response) => {
            this.buildingList = response.rows;
          });
          this.form = response.data;
          this.form.fileIdList = [];
          this.form.fileList.forEach((element) => {
            this.form.fileIdList.push({
              name: element.name,
              id: element.id,
              url: "http://" + element.url,
            });
          });
          this.open = true;
          this.title = "修改房源";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            let data = JSON.parse(JSON.stringify(this.form));
            data.fileIdList = this.$refs.fileupload.fileList.map(
              (item) => item.id
            );
            if (this.form.id != null) {
              updateBuiRoom(data).then((response) => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addBuiRoom(data).then((response) => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除房源编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return delBuiRoom(ids);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download(
          "park/buiRoom/export",
          {
            ...this.queryParams,
          },
          `park_buiRoom.xlsx`
        );
      },
    },
  };
</script>
<style scoped lang='scss'>
  .facilityList {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    span {
      flex-shrink: 0;
      margin-left: 10px;
    }
    .el-input {
      margin-left: 10px;
    }
    i {
      font-size: 20px;
      margin-left: 10px;
      cursor: pointer;
    }
  }
</style>
